<{capture name="header"}>
<{css app="ome" src="ome.css"}>
<{css app="ome" src="style.css"}>
<{script src="coms/autocompleter.js" app="desktop"}>
<{script src="coms/pager.js" app="desktop"}>
<{/capture}>
<form method="post" id="fm1" action="index.php?app=taoguanallocate&ctl=admin_appropriation&act=do_save">
  <input type="hidden" name="appropriation_type" id="appropriation_type" value="1" />
  <div class="tableform">
    <h3>调拨单信息</h3>
    <div class="division">
      <h5>调拨仓库</h5>
      <table border="0" cellspacing="0" cellpadding="0" class="gridlist">
         <tbody>
          <tr>
            <th colspan="2">采购单编号搜索：<input type="text" name="text" id="selectPurchase" >(输入采购单号后回车即可)
           &nbsp;&nbsp;
              <input type="button" name="cleanPurchase" id='cleanPurchase' value="清空采购单载入数据">
             
            </td>
            <th></th>
            <td>
                
          </tr>
          <tr>
            <th>调出仓库：</th>
            <td>
               <{if $is_super}>
              <{if count($branch)=='1'}>
              <{$branch.0.name}>
              <select id="from_branch_id" name="from_branch_id" style="display:none;">
                <option value="<{$branch.0.branch_id}>"><{$branch.0.name}></option>
              </select>
              <{else}>
                        <select name="from_branch_id" id="from_branch_id">
                            <option value="">--请选择--</option>
                            <{foreach from=$branch item=item}>
                            <option value='<{$item.branch_id}>'  <{if $from_branch_check == $item.branch_id}>selected="selected"<{/if}>><{$item.name}></option>
                            <{/foreach}>
                        </select><span style="color:red">*</span> <{/if}>
              <{else}>
              <{if !$branch_list}> <font color="red">* 当前没有操作仓库的权限，请联系管理员分配。  *</font>
              <script>
                       $$("input","button","select").set('disabled',true);
                    </script>
              <{else}>
              <{if count($branch_list)=='1'}>
              <{$branch_list.0.name}>
              <select id="from_branch_id" name="from_branch_id" style="display:none;">
                <option value="<{$branch_list.0.branch_id}>"><{$branch_list.0.name}></option>
              </select>
              <{else}>
                     <select name="from_branch_id" id="from_branch_id">
                            <option value="">--请选择--</option>
                            <{foreach from=$branch_list item=item}>
                            <option value='<{$item.branch_id}>' <{if $from_branch_check == $item.branch_id}>selected="selected"<{/if}>><{$item.name}></option>
                            <{/foreach}>
                      </select><span style="color:red">*</span> <{/if}>
              <{/if}>
              <{/if}>
             
            </td>
            <th>调入仓库：</th>
            <td>
                <select name="to_branch_id" id="to_branch_id">
                    <option value="">--请选择--</option>
                    <{foreach from=$all_branch item=item}>
                        <option value='<{$item.branch_id}>' <{if $to_branch_check == $item.branch_id}>selected="selected"<{/if}>><{$item.name}></option>
                    <{/foreach}>
                </select>
                <span style="color:red">*</span>
              <{if !$branch_list}> <font color="red">* 当前没有操作仓库的权限，请联系管理员分配。  *</font>
              <script>
                       $$("input","button","select").set('disabled',true);
                    </script>
              <{/if}>
          </tr>
        </tbody>
      </table>
      <h5 style="margin-top:10px;">调拨商品</h5>
      <{button label="商品库频道" id="allocate-find-btn" }>
       <span id='pfba'>
      <label>按基础物料编码索引：</label>
      <input type="text" name="bn" />
      </span>
      <span id='pfba2'>
      <label>按基础物料名称索引：</label>
      <input name="name" type="text" size="35" />
      </span>
      <span id='pfba3'>
        <label>按条形码索引：</label>
        <input type="text" name="barcode" />
      </span>
      <table class="gridlist" id="appropriation_table"  style="margin:4px 0;">
        <thead>
          <tr>
          <th><input type="checkbox" class='selectall' onclick="this.blur()"></th>
            <th>基础物料编码</th>
            <th style="width:240px;">基础物料名称</th>
            <th>规格</th>
            <th>货位</th>
            <th>条形码</th>
            <th>原仓数量</th>
            <th>新仓数量</th>
            <th>数量</th>
            <th style="display:none;">合计金额</th>
            <th style="width:30px;">删除</th>
          </tr>
        </thead>
        <tbody id="dataNode">
          <tr>
            <td colspan="9" style="padding:0;"><div class="note" style="margin:0;"> 暂无货品信息 </div></td>
          </tr>
        </tbody>
      </table>
      <div align="right">
        调拨总量: <span id="buy_count">0</span> <span id="buy_amount" style="display:none;">0</span> &nbsp; <{button label="删除选中" id="appropriation-del-btn"}> &nbsp;<{button type="button" id="appropriation-delall-btn" label="全部删除" }></div> </div>  
    <table width="100%" border="0" cellpadding="0" cellspacing="0" style="margin-top:10px;">
      <tr>
        <td width="10%" align="right">备注:</td>
        <td align="left"><textarea id="memo" maxth="255" rows="3" cols="80%" name="memo" type="textarea"></textarea></td>
      </tr>
      <tr>
        <td align="right">经办人:</td>
        <td align="left"><input name="operator" type="text" value="<{$operator}>" size="15" vtype="required"/></td>
      </tr>
    </table>
    <div id="cc" class="noprint table-action"> 
    <{if $appropriation_type == 'directly'}>
    <{button type="button" id="saveCurrent" label="直接调拨"}>
    <{else}>
    <{button type="button" id="return-btn" label="出入库调拨"}>
    <{/if}>
    </div>
  </div>
</form>
<script>
(function(){
var visiTips = new Tips({
        onShow:function(tip,el){
            el.addClass('active');
            tip.setStyle('display','block');
        },
        text: function(element){
            if(element.get('visibility')=='false'){
                return '不可售商品';
            }else{
                return '';
            }
        }
    });

    var callurl='index.php?app=taoguanallocate&ctl=admin_appropriation&act=getProducts&p[0]='+$('from_branch_id').value + '&p[1]='+$('to_branch_id').value,store=[];
    var options={
        'getVar':'bn',
        'fxOptions':false,
        callJSON:function(){return window.autocompleter_json;},
        injectChoice:function(json){    
            var choice = new Element('li', {'html': this.markQueryValue(json[this.options.getVar])});
            choice.store('_data',json);
            choice.inputValue = json[this.options.getVar];
            this.addChoiceEvents(choice).inject(this.choices);
        },
        onHide:function(){
            if(!this.selected)return;
            var json=this.selected.retrieve('_data');
            json=$splat(json);
            init(json);
            MessageBox.success('加载商品成功!!');
        },
        onFocus:function(ipt){
            this.url = 'index.php?app=taoguanallocate&ctl=admin_appropriation&act=getProducts&p[0]='+$('from_branch_id').value + '&p[1]='+$('to_branch_id').value;
            ipt.value='';
        }
    };
   
    var last_from_branch_id = 0;
    $('from_branch_id').addEvent('click',function(e){
        last_from_branch_id = $('from_branch_id').value;
    });
    
    $('from_branch_id').addEvent('change',function(e){
        if($('from_branch_id').value == $('to_branch_id').value){
            for(var i=0;i<$('from_branch_id').options.length;i++){
                if($('from_branch_id').options[i].value == last_from_branch_id){
                    $('from_branch_id').options[i].selected = true;
                }
                
            }
            alert('调出仓库跟调入仓库不能一致！');
             return false;
        }
        
        if(!pag||!pag.data)return;
        var delarr=[];var delNum = [];
        pag.data.each(function(d){
             delarr.push(d['product_id']);
             delNum[d['product_id']] = d['num'];
        });
        if(delarr.length){
            delProduct(pag,delarr);
            $('buy_count').set('text',0);
            $('buy_amount').set('text',0);
            //emptyData();

            new Request({url:'index.php?app=taoguanallocate&ctl=admin_appropriation&act=getProducts&p[0]='+$('from_branch_id').value + '&p[1]='+$('to_branch_id').value, method:'post',data:{'product_id':delarr},
              onSuccess:function(json){
                if(!json) return;
                rs=JSON.decode(json);
                var total = 0;
                rs.each(function(item,index){
                    rs[index].num = delNum[item.product_id];
                    total += item.num.toInt();
                });
                init(rs);
                $('buy_count').set('text', total);
              }
            }).send();
        }
    });
    
    var last_to_branch_id = 0;
    $('to_branch_id').addEvent('click',function(e){
        last_to_branch_id = $('to_branch_id').value;
    });
    $('to_branch_id').addEvent('change',function(e){
        if($('to_branch_id').value == $('from_branch_id').value){
            for(var i=0;i<$('to_branch_id').options.length;i++){
                if($('to_branch_id').options[i].value == last_to_branch_id){
                    $('to_branch_id').options[i].selected = true;
                }
                
            }
            alert('调出仓库跟调入仓库不能一致！');
             return false;
        }
        if(!pag||!pag.data)return;
        var delarr=[]; var delNum = [];
        pag.data.each(function(d){
             delarr.push(d['product_id']);
             delNum[d['product_id']] = d['num'];
        });

        if(delarr.length){
            delProduct(pag,delarr);
            $('buy_count').set('text',0);
            $('buy_amount').set('text',0);
            //emptyData();

            new Request({url:'index.php?app=taoguanallocate&ctl=admin_appropriation&act=getProducts&p[0]='+$('from_branch_id').value + '&p[1]='+$('to_branch_id').value, method:'post',data:{'product_id':delarr},
              onSuccess:function(json){
                if(!json) return;
                rs=JSON.decode(json);
                var total = 0;
                rs.each(function(item,index){
                    rs[index].num = delNum[item.product_id];
                    total += item.num.toInt();
                });
                init(rs);
                $('buy_count').set('text', total);
              }
            }).send();
        }
    });

    new Autocompleter.script($E('#pfba input'),callurl, options);
    new Autocompleter.script($E('#pfba2 input'),callurl,$merge(options,{'getVar':'name'}));
	new Autocompleter.script($E('#pfba3 input'),callurl,$merge(options,{'getVar':'barcode'}));

    var tpl='<tr key="{product_id}" id="product_{product_id}" title="点击选取/反选此条记录">'+
        '<td><input type="checkbox" class="product_select"></td><td><input type="hidden" name="product_id[]" value="{product_id}" />{bn}</td><td class="product-name" visibility="{visibility}">{name}</td><td>{spec_info}</td><td>{store_position}</td><td>{barcode}</td>'+
        '  <td><input type="hidden" value="{from_branch_num}" key="from_branch_num" tname="from_branch_num[_PRIMARY_]" />{from_branch_num}</td>'+
        '  <td><input type="hidden" value="{to_branch_num}" key="to_branch_num" tname="to_branch_num[_PRIMARY_]" />{to_branch_num}</td>'+
        '  <td><input type="text" value="{num}" key="num" vtype="unsigned&amp;&amp;required" tname="at[_PRIMARY_]" size="6"></td>'+
        '  <td class="count" style="display:none;"><input type="hidden" tname="pr[_PRIMARY_]" key="price" value="{price}" size="8">{count}</td>'+
        '  <td><{img src="bundle/delecate.gif" app="desktop" key="state" class="pointer btn-delete-item"}></td>'+
        '</tr>';

    $('allocate-find-btn').addEvent('click',function(e){
        var url='index.php?app=desktop&act=alertpages&goto='+encodeURIComponent('index.php?app=taoguanallocate&ctl=admin_appropriation&act=findProduct');
        Ex_Loader('modedialog',function() {
            var callurl='index.php?app=taoguanallocate&ctl=admin_appropriation&act=getProducts&p[0]='+$('from_branch_id').value + '&p[1]='+$('to_branch_id').value;
            new finderDialog(url,{params:{url:callurl,name:'product_id[]'},width:1000,height:660,
                onCallback:function(rs){
                    if(!rs)return;
                    rs=JSON.decode(rs);
                    init(rs);
                }
            });
        });
    });

    var pag;
    function emptyData(){
        var noData='<tr>'+
            '<td colspan="9" style="padding:0;"><div class="note" style="margin:0;"> 暂无货品信息 </div></td>'+
            '</tr>';
        $('dataNode').set('html',noData);
    }
    function createProduct(data){
        pag=new PageData(tpl,data,{'updateMain':$('dataNode'),'pageNum':10000,
            'format': function(d) {
                d.count = (d.num * d.price).toFixed(3);
            },
            'onShow':function(){
                var _this=this;
                /*$$('#dataNode input[type]').addEvent('change',function(e){
                    var pid=this.getParent('tr').get('key'),value=this.value;
                    _this.editData(pid,[this.get('key'),value]);
                });*/
                $$('#dataNode input[tname$="[_PRIMARY_]"]').each(function(item){
                    item.store('initval',item.value).addEvent('change',function(e){
                        var patten,
                            parent = this.getParent('tr'),
                            pid= parent.get('key'),
                            value= this.value,
                            diffval = this.retrieve('initval') - value;
                            //alert(this.retrieve('initval'));
                        if (/^at\[/.test(this.get('tname'))){
                            patten = /^[1-9]\d*$/;
                        }else{
                            patten = /^\d+(\.*)\d*$/;
                        }
                        if(!patten.test(value)){
                            this.focus();
                            this.select();
                            return MessageBox.error('输入格式有误！');
                        }
                        this.store('initval', value);
                        _this.editData(pid,[this.get('key'),value]);

                        var count = parent.getElement('td.count'),
                            num = _this.selectData(pid).num.toInt(),
                            pr = 0,//_this.selectData(pid).price.toFloat(),
                            sums = (num * pr).toFixed(3);

                        count.set('text',sums);

                        _this.editData(pid,['count',sums]);
                        if (/^at\[/.test(this.get('tname'))){
                            $('buy_count').set('text', $('buy_count').get('text') - diffval);
                            $('buy_amount').set('text', ($('buy_amount').get('text') - diffval * pr).toFixed(3));
                        }else{
                            $('buy_amount').set('text', ($('buy_amount').get('text') - diffval * num).toFixed(3));
                        }
                    });
                });
                /*var state=this.curdata.every(function(d){return d['state']=='checked';});
                $('appropriation-delall-btn').checked=!state?false:true;
                attachEsayCheck($('dataNode'),'input[type=checkbox]');*/
                $$('#dataNode tr').each(function(item,i){
                    item.addEvent('click',function(e){
                        //e.stop();
                        this.toggleClass('selected');
                        _this.selectData(this.get('key')).selected = _this.selectData(this.get('key')).selected && _this.selectData(this.get('key')).selected === true ? false : true;
                        var selectflag = _this.selectData(this.get('key')).selected;
                        var selectproduct = item.getElement('.product_select');
                        if (selectflag)
                        {
                            selectproduct.set('checked','checked');
                        }else{
                            selectproduct.set('checked','');
                        }
                    });
                    item.getElement('.btn-delete-item').addEvent('click',function(e){
                        e.stop();
                        if(_this.selectData(item.get('key')) && confirm('确定要删除 '+ _this.selectData(item.get('key'))['name'] +' 吗？')){
                          compute(item);
                          _this.delData(item.get('key'));
                        }
                        if(!$E('#dataNode tr')) emptyData();
                    });
                    item.getElement('input[tname^=at]').addEvent('enter',function(e){
                        $E('#pfba input').focus();
                    });
                });
                
                //var len = this.data.length ? (this.data.length > this.options.pageNum ? (this.options.current == this.getTotal() ? this.data.length-this.options.pageNum*(this.options.current-1) : this.options.pageNum) : this.data.length) : 0;
                if(this.data.length) $E('#dataNode input[key^=num]').focus();
                $ES('.product-name').each(function(item){
                    if(item.get('visibility')=='false'){
                        item.setStyle('color','#808080');
                    }
              });
              $ES('.product-name').removeEvent('mouseover').addEvent('mouseover',function(e){
                    if (this.get('visibility')=='false')
                    {
                        var e  = new Event(e), el = e.target;
                        visiTips.attach(el);
                        el.addEvent('mouseleave',function(){
                            this.removeClass('active');
                        });
                        el.fireEvent('mouseenter',e);
                    }
              });
            }
        });
    }

    $('appropriation-delall-btn').addEvent('click',function(e){
        if(!pag||!pag.data)return;
        var delarr=[];
        pag.data.each(function(d){
             delarr.push(d['product_id']);
        });
        if(delarr.length && confirm('确认删除全部调拨商品吗？')){
            delProduct(pag,delarr);
            $('buy_count').set('text',0);
            $('buy_amount').set('text',0);
            emptyData();
        }
    });

    $('appropriation-del-btn').addEvent('click',function(e){
        if(!pag||!pag.data)return;
        var delarr=[];
        pag.data.each(function(d,i){
            if(pag.selectData(d['product_id']).selected && pag.selectData(d['product_id']).selected === true) delarr.push(d['product_id']);
        });
        if(delarr.length){
          if(confirm('确认删除选定的调拨商品吗？')){
            var nums=0,prices=0,sums=0;
            delarr.each(function(id,i){
              nums += pag.selectData(id).num.toInt();
              //prices += pag.selectData(id).price.toFloat();
              //sums += pag.selectData(id).num.toInt() * pag.selectData(id).price.toFloat();
            });
            $('buy_count').set('text',$('buy_count').get('text') - nums);
            $('buy_amount').set('text',($('buy_amount').get('text') - sums).toFixed(3));
            delProduct(pag,delarr);
          }
            if(!$E('#dataNode tr')) emptyData();
        }
        else MessageBox.error("请先选择欲删除的调拨商品！");
    });
    function compute(e){
      var num = e.getElement('input[tname="at[_PRIMARY_]"]').value.toInt();
      var pr = e.getElement('input[tname="pr[_PRIMARY_]"]').value.toFloat();
      var sum = num * pr;
      $('buy_count').set('text',$('buy_count').get('text') - num);
      $('buy_amount').set('text',($('buy_amount').get('text') - sum).toFixed(3));
    }

    function init(rs){
        var tmparr=findProduct(rs,'product_id');
         store.unshift.apply(store,tmparr.reverse());
         createProduct(store);
    }
    function findProduct(arr,PRIMARY){
        if(!store.length)return arr;
        store.each(function(a){
            arr.each(function(b){
                if(a[PRIMARY]==b[PRIMARY])
                {
                    
                    a.num=b.num;
                    arr.erase(b);
                }
            });
        });
        return arr;
    }
    function delProduct(obj,arr){
        arr.each(function(d){obj.delData(d);});
    }
    
    if($('saveCurrent')){
        $('saveCurrent').addEvent('click',function(e){
            $('appropriation_type').value = 1;
            doSubmit(this,e);
        });
    }
    
    if($('return-btn')){
    $('return-btn').addEvent('click',function(e){
        $('appropriation_type').value = 2;
        doSubmit(this,e);
    });
    }
    
    function doSubmit(el,e){
        var _this=el;
        var form=el.getParent('form');
        if(pag){
            var data=pag.toHideInput($('dataNode').getElement('tr'));
            form.store('target',{extraData:data,
                onRequest:function(){
                    _this.disabled=true;
                },
                onComplete:function(jsontext){
                    try{
                        var json = JSON.decode(jsontext);
                        if (typeof(json.error)!='undefined'){
                            _this.disabled=false;
                        }else{
                            _this.disabled=true;
                            if(opener.finderGroup['<{$env.get.finder_id}>']) opener.finderGroup['<{$env.get.finder_id}>'].refresh.delay(100,opener.finderGroup['<{$env.get.finder_id}>']);
                            setTimeout('window.close()',200);
                        }
                    }catch(e){}
                }
            });
        }
        form.fireEvent('submit',e);
    }

    $('selectPurchase').addEvent('enter',function(e){
        var purchase_bn = this.value;
        if (purchase_bn){
        
            new Request({url:'index.php?app=taoguanallocate&ctl=admin_appropriation&act=getPurchaseBybn&p[0]='+purchase_bn+'&p[1]='+$('from_branch_id').value + '&p[2]='+$('to_branch_id').value, method:'get',
              onRequest: function(){
                MessageBox.show('正在加载...');
              },
              onSuccess:function(json){
                if(!json) return;
                rs=JSON.decode(json);
                //采购信息载入

                //$('to_branch_id').getElement('option[value='+rs.branch_id+']').selected=true;
                init(rs.items);
                $('buy_count').set('text',rs.total_nums);
                
              }
            }).send();
    
        }
    });

    $('cleanPurchase').addEvent('click',function(e){
        $('to_branch_id').options[0].selected=true;
        emptyData();
        $('buy_count').set('text',0);
    });

    $E('.selectall').addEvent('click',function(e){
    
       if (this.checked)
        {
            $ES('.product_select').set('checked','checked');
            $$('.product_select').each(function(item){
                protr = item.getParent('tr');
                product_id = protr.get('key');
                protr.addClass('selected');
                pag.selectData(product_id).selected=true;
            
            });
        }else{
            $ES('.product_select').set('checked','');
            $$('.product_select').each(function(item){
                protr = item.getParent('tr');
                product_id = protr.get('key');
                protr.removeClass('selected');
                pag.selectData(product_id).selected=false;
            
            });
        }
        
    
    
    });

})();

</script>